<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>改变DOM树练习</title>
    <style>
      .red {
        color: red;
      }
      .blue {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h1>DOM Tree</h1>
    <ul id="list">
      <li class="red">list-item 1</li>
      <li>list-item 2</li>
      <li>list-item 3</li>
      <li>list-item 4</li>
    </ul>
    <input type="button" value="改变列表" onclick="changeList()" />
    <script>
      function changeList() {
        const ul = document.querySelector("#list");
        const it2 = ul.children[1];
        it2.classList.toggle("blue");
        if (ul.children.length === 4) {
          const nw = document.createElement("li");
          nw.textContent = "list-item New";
          ul.children[1].after(nw);
          const head = ul.firstElementChild.cloneNode(true);
          const back = ul.lastElementChild.cloneNode(true);
          ul.firstElementChild.replaceWith(back);
          ul.lastElementChild.replaceWith(head);
        } else {
          ul.children[2].remove();
          const head = ul.firstElementChild.cloneNode(true);
          const back = ul.lastElementChild.cloneNode(true);
          ul.firstElementChild.replaceWith(back);
          ul.lastElementChild.replaceWith(head);
        }
      }
    </script>
  </body>
</html>
